package esercitazione3.jUnitTest;

import java.util.Iterator;

import org.junit.*;

import esercitazione3.tda_BinaryTree.*;
import esercitazione3.tda_Dictionary.Entry;
import esercitazione3.tda_Dictionary.InvalidEntryException;
import esercitazione3.tda_Dictionary.InvalidKeyException;
import esercitazione3.tda_NodeList.NodePositionList;
import static org.junit.Assert.*;

public class BinarySearchTreeTest{
	
	private BinarySearchTree<Integer,String> bsTree;
	
	@Before
	public void setUp(){
		bsTree = new BinarySearchTree<Integer, String>();
	}
	
	
	@Test
	public void testInsert() throws InvalidKeyException{
		
		assertEquals(new Integer(5), bsTree.insert(5, "Ciao").getKey());
		assertEquals(new Integer(1), bsTree.insert(1, "Casa").getKey());
		assertEquals("Cibo", bsTree.insert(2, "Cibo").getValue());
		assertNotEquals("Cibo", bsTree.insert(2, "Chiesa").getValue());
		
	}
	
	
	@Test
	public void testFind() throws InvalidKeyException{
		
		bsTree.insert(5, "Ciao");
		bsTree.insert(1, "Casa");
		bsTree.insert(2, "Cibo");
		
		assertEquals(new Integer(5), bsTree.find(5).getKey());
		assertNotEquals(new Integer(24), bsTree.find(5).getKey());
		assertNull(bsTree.find(25));
		
	}
	
	
	@Test
	public void testFindAll() throws InvalidKeyException{
		
		bsTree.insert(5, "Ciao");
		bsTree.insert(1, "Casa");
		bsTree.insert(2, "Cibo");
		bsTree.insert(2, "Cane");
		
		assertEquals(2, ((NodePositionList<Entry<Integer,String>>)bsTree.findAll(2)).size());
		
		Iterator<Entry<Integer, String>> it = ((NodePositionList<Entry<Integer,String>>)bsTree.findAll(2)).iterator();
		
		// La find all restituisce i risultati ordinati secondo l'ordine imposto dalla funzione
		// interna treeSearch.
		assertEquals("Cane", it.next().getValue());
		assertEquals("Cibo", it.next().getValue());
		
	}
	
	
	@Test(expected=InvalidEntryException.class)
	public void testRemove() throws InvalidEntryException, InvalidKeyException{
		
		bsTree.insert(5, "Ciao");
		bsTree.insert(2, "Cibo");
		bsTree.insert(1, "Chiesa");
		bsTree.insert(10, "Ciabatta");
		
		assertEquals(new Integer(2), bsTree.remove(bsTree.find(2)).getKey());
		assertNull(bsTree.remove(bsTree.find(65)));
		assertNotNull(bsTree.find(1));
		
	}
	
	
	@Test
	public void testEntries() throws InvalidKeyException{
		
		bsTree.insert(5, "Ciao");
		bsTree.insert(2, "Cibo");
		bsTree.insert(1, "Chiesa");
		bsTree.insert(10, "Ciabatta");
		
		Iterator<Entry<Integer, String>> it = bsTree.entries().iterator();
		
		assertEquals("Ciao", it.next().getValue());
		assertEquals(new Integer(2), it.next().getKey());
		assertEquals("Chiesa", it.next().getValue());
		assertEquals(new Integer(10), it.next().getKey());

	}

}
